package com.zzoranor.presentationserver;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import protocols.ProtocolsProto.AddCharacter;
import protocols.ProtocolsProto.CharacterMessage;
import protocols.ProtocolsProto.ClientToServerMessage;
import protocols.ProtocolsProto.HelloWorld;

import com.zzoranor.util.Log;

/**
 * The purpose of this class is to listen on a client 
 * socket provided by a ClientInfo object, and reading 
 * messages from that client. 
 * 
 * It forwards these messages to the server dispacher for 
 * queueing and execution. 
 * @author Tim
 *
 */
public class ClientListener extends Thread {

	private ClientInfo clientInfo;
	private ServerDispatcher serverDispatcher;
	private ClientToServerMessageHandler clientToServerMessageHandler;
	private DataInputStream in;
	
	public ClientListener(ClientInfo clientInfo, ServerDispatcher serverDispatcher, ClientToServerMessageHandler clientToServerMessageHandler) {
		this.clientInfo = clientInfo;
		this.serverDispatcher = serverDispatcher;
		this.clientToServerMessageHandler = clientToServerMessageHandler;
	}
	
	public void setup()
	{
		try {
			in = new DataInputStream(clientInfo.getSocket().getInputStream());
			
		} catch (IOException e) {
			Log.printStackTrace(e);
		}
	}
	
	public void run()
	{
		try
		{
			while(!isInterrupted())
			{
				byte size = (byte) in.read();
				if(size == -1)
				{
					// EOF
					break;
				}
				byte [] bytes = new byte[size];
				in.readFully(bytes);
				ClientToServerMessage msg = ClientToServerMessage.parseFrom(bytes);
				Log.d(msg.toString());
				
				clientToServerMessageHandler.handle(clientInfo, msg);
				
				
			}
		}catch(IOException e)
		{
			Log.printStackTrace(e);
		}
		finally
		{
			try {
				if(in != null)
					{
					in.close();
					}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		
		clientInfo.getSender().interrupt();
		serverDispatcher.deleteClient(clientInfo);
	}

}
